# coding=utf-8
from datetime import datetime

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many


def record_dds() -> bool:
    asapi_data = request_asapi(1, "Dds", "2015-12-01", "DescribeDBInstances")
    if not asapi_data:
        return False
    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for i in asapi_data['DBInstances']['DBInstance']:
        tmp_tuple = (
            i['DBInstanceId'], i['DBInstanceDescription'], i['DBInstanceType'], i['DBInstanceStorage'],
            i['DBInstanceClass'], i['Engine'], i['EngineVersion'], i['ReplicationFactor'], i['ResourceGroup'],
            i['ResourceGroupName'], i['Department'], i['DepartmentName'], i['NetworkType'], i['LockMode'],
            i['DBInstanceStatus'], i['CreationTime'], datetime.now())
        values_list.append(tmp_tuple)
    table = 'c_dds_info'
    fields = "instance_id,instance_description,instance_type,instance_storage,instance_class,engine,engine_version," \
             "replication_factor,resource_group,resource_group_name,department,department_name,network_type,lock_mode," \
             "status,create_time,record_time"
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_dds_info', methods=['POST'])
def record_dds_api():
    success = record_dds()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
